<?php

namespace Yond\LaravelDomain\Console;

use Yond\LaravelDomain\Console\Traits\ParserTrait;

abstract class GeneratorCommand extends Command
{
    use ParserTrait;

    /**
     * @return bool|null
     */
    public function handle()
    {
        // $userData = [
        //     'path' => [
        //         'domain-path' => config('yond-domain.path.domain'),
        //         'domain-name' => 'Exam',
        //         'app-path' => config(yond-domain.path.app),
        //         'app-name' => 'Admin',
        //         'file-name' => $this->className,
        //     ],
        //     'stub' => [
        //         'class' => $this->className,
        //         'nameSpace' => $nameSpace,
        //     ]
        // ];
        $userData = $this->getUserInputs();

        if ($userData === null) {
            return false;
        }

        $userData = $this->sanitizeUserData($userData);

        $path = $this->parsePath($this->getPathStructure(), $userData['path']);

        if ((! $this->hasOption('force') ||
                ! $this->option('force')) &&
            $this->alreadyExists($path)) {
            $this->error($path.' already exists!');

            return false;
        }

        $this->ensureDirectoryExists(dirname($path));

        $stub = $this->parseStubContent($this->getStub($this->getStubName()), $userData['stub']);

        $this->files->put($path, $this->sortImports($stub));

        $this->info($path.' created successfully.');

        return 0;
    }

    abstract protected function getUserInputs();
    abstract protected function getStubName();
    abstract protected function getPathStructure();

    private function sanitizeUserData($data)
    {
        if (!array_key_exists('path', $data)) {
            $data['path'] = [];
        }

        if (!array_key_exists('stub', $data)) {
            $data['stub'] = [];
        }

        return $data;
    }

    protected function sortImports($stub)
    {
        if (preg_match('/(?P<imports>(?:use [^;]+;$\n?)+)/m', $stub, $match)) {
            $imports = explode("\n", trim($match['imports']));

            sort($imports);

            return str_replace(trim($match['imports']), implode("\n", $imports), $stub);
        }

        return $stub;
    }



















}
